/* eslint-disable no-async-promise-executor */
const model = require("../models/model")
const { getFile } = require('../models/getfile')
// 获取商品一级分类
exports.getOne = async(ctx) => {
  const CategoryOne = model.categoryOne.CategoryOne //获取模型
  const res = await CategoryOne.findAll()
  if (res) {
    ctx.success(res)
  } else {
    ctx.fail('获取失败')
  }
}
// 根据一级id获取二级分类
exports.getTwo = async(ctx) => {
  const { parentId } = ctx.request.query
  const where = {
    parentId: parentId ? parentId : undefined
  }
  for (const prop in where) {
    if (!where[prop]) {
      delete where[prop]
    }
  }
  const CategoryTwo = model.categoryTwo.CategoryTwo //获取模型
  const res = await CategoryTwo.findAll({ where })
  if (res.length > 0) {
    let flag = 0
    for (let i = 0; i < res.length; i++) {
      await getFile(res[i].icon).then(url => { // 获取图片
        flag++
        res[i].icon = url
        if (flag === res.length) {
          ctx.success(res)
        }
      })
    }
  } else {
    ctx.fail('该分类未有数据')
  }
}
exports.modify = async(ctx) => {
  const data = ctx.request.body
  if (!data.className || !data.name) {
    ctx.fail('参数错误')
    return
  }
  const Models = data.className === 'one' ? model.categoryOne.CategoryOne : model.categoryTwo.CategoryTwo
  function edit() {
    return new Promise(async(resolve) => {
      const res = await Models.update(data, { where: { id: data.id }})
      if (res[0] == 1) {
        resolve('修改成功')
      } else {
        resolve(-1)
      }
    })
  }
  function add() {
    return new Promise(async(resolve) => {
      const res = await Models.create(data)
      if (res) {
        resolve('添加成功')
      } else {
        resolve(-1)
      }
    })
  }
  let res
  if (data.id) { // 修改
    res = await edit()
  } else { // 新增
    res = await add()
  }
  if (res !== -1) {
    ctx.success('', res)
  } else {
    ctx.fail()
  }
}
exports.delete = async(ctx) => {
  const { className, id } = ctx.request.query
  if (!className || !id) {
    ctx.fail('参数错误')
    return
  }
  const Models = className === 'one' ? model.categoryOne.CategoryOne : model.categoryTwo.CategoryTwo
  const res = await Models.destroy({ where: { id: id }})
  if (res) {
    ctx.success('', '删除成功')
  } else {
    ctx.fail('删除失败')
  }
}
